package com.zhai.domain.strategy.service.armory;

import cn.hutool.core.util.StrUtil;
import com.zhai.domain.strategy.model.entity.StrategyAwardEntity;
import com.zhai.domain.strategy.model.entity.StrategyEntity;
import com.zhai.domain.strategy.model.entity.StrategyRuleEntity;
import com.zhai.domain.strategy.repository.IStrategyRepository;
import com.zhai.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

import static com.zhai.types.common.Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY;
import static com.zhai.types.common.Constants.UNDERLINE;
import static com.zhai.types.enums.ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL;

/**
 * @Description: 策略装配库（兵工厂），负责初始化策略计算
 * @ClassName: StrategyAmory
 * @Author: zhaiyongxin
 * @Date: 2024/12/31 11:06
 * @Version: 1.0
 */
@Service
@Slf4j
public abstract class AbstractStrategyAlgorithm implements IStrategyArmory, IStrategyDispatch{

    @Resource
    protected IStrategyRepository repository;

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = repository.queryStrategyIdByActivityId(activityId);
        return this.assembleLotteryStrategy(strategyId);
    }

    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        // 1.查询策略奖品配置
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);

        //缓存库存
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardCount = strategyAwardEntity.getAwardCountSurplus();
            Integer awardId = strategyAwardEntity.getAwardId();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        this.armoryAlgorithm(String.valueOf(strategyId), strategyAwardEntities);

        // 2. 权重策略配置 - 适用于 rule_weight 权重规则配置
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        if (null == strategyEntity) {
            return false;
        }

        String ruleWeight = strategyEntity.getRuleWeight();
        if (null == ruleWeight) {
            return true;
        }
        //查询权重列表 rule_weight 6000,102,103,104,105,106,107,108,109
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
        if (StrUtil.isEmpty(strategyRuleEntity.getRuleModel())){
            throw new AppException(STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        //获取规则权重列表
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();

        //按权重装配
        for (String key : ruleWeightValueMap.keySet()) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            this.armoryAlgorithm(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return true;

    }

    /**
     * 装配算法
     * @param key 为策略ID、权重ID
     * @param strategyAwardEntities 对应的奖品概率
     */
    protected abstract void armoryAlgorithm(String key, List<StrategyAwardEntity> strategyAwardEntities);

    /**
     * 调度算法抽奖
     * @param key
     * @return
     */
    protected abstract Integer dispatchAlgorithm(String key);

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = STRATEGY_AWARD_COUNT_KEY + strategyId + UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }

    public boolean assembleLotteryStrategy(String cacheKey, List<StrategyAwardEntity> strategyAwardEntities) {
        // 1.获取最小概率值
        BigDecimal minAwareRate = minAwareRate(strategyAwardEntities);
        // 2.获取概率总和 如果加和值不为1
        BigDecimal totalAwardRate = strategyAwardEntities.stream().map(StrategyAwardEntity::getAwardRate).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (totalAwardRate.doubleValue() > 100) {
            log.error("概率值不能大于100%");
            return false;
        }
        // 3.获取概率范围：总范围/最小范围=概率范围
        BigDecimal rateRange = totalAwardRate.divide(minAwareRate, 0, RoundingMode.CEILING);

        // 4.填充奖品检索表，每个奖品占用多少空间都被规定好了
        ArrayList<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAwardEntity  : strategyAwardEntities) {
            BigDecimal awardRate = strategyAwardEntity.getAwardRate();
            Integer awardId = strategyAwardEntity.getAwardId();

            //计算每个概率值存放到查找表的数量，填充
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }

        }

        // 5.将集合乱序，避免奖品堆放顺序一致
        Collections.shuffle(strategyAwardSearchRateTables);

        // 6.生成出Map集合，key值，对应的就是后续的概率值。通过概率来获得对应的奖品ID
        HashMap<Integer, Integer> shuffledStrategyAwardSearchRateTable = new HashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffledStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        // 8.存储到redis
        repository.storeStrategyAwardSearchRateTables(cacheKey, shuffledStrategyAwardSearchRateTable.size(), shuffledStrategyAwardSearchRateTable);

        return true;
    }

    /**
     * 获取最小概率值
     * @param strategyAwardEntities
     * @return
     */
    protected static BigDecimal minAwareRate(List<StrategyAwardEntity> strategyAwardEntities) {
        BigDecimal minAwareRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
        return minAwareRate;
    }

    /**
     * 根据传入的最小概率值计算范围值
     * @param min
     * @return
     */
    protected double convert(BigDecimal min) {
        if (BigDecimal.ZERO.compareTo(min) == 0) return 1D;
        String minStr = min.toString();
        // 小数点前
        String beginVale = minStr.substring(0, minStr.indexOf("."));
        int beginLength = 0;
        if (Double.parseDouble(beginVale) > 0) {
            beginLength = minStr.substring(0, minStr.indexOf(".")).length();
        }
        // 小数点后
        String endValue = minStr.substring(minStr.indexOf(".") + 1);
        int endLength = 0;
        if (Double.parseDouble(endValue) > 0) {
            endLength = minStr.substring(minStr.indexOf(".") + 1).length();
        }
        return Math.pow(10, beginLength + endLength);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        int rateRange = repository.getRateRange(String.valueOf(strategyId));
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        int rateRange = repository.getRateRange(key);
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    /**
     * 根据策略ID和奖品ID，扣减奖品缓存库存
     *
     * @param strategyId 策略ID
     * @param awardId    奖品ID
     * @return 扣减结果
     */
    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = STRATEGY_AWARD_COUNT_KEY + strategyId + UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey, endDateTime);
    }
}
